<template>
  <base-panel :show.sync="show" :diy-transfer="true" :re="true" width="400px" class="notification-center">
    <div class="normal-note-box" slot="diyTransferCon">
      <div class="normal-note-right-box">
        <div class="normal-tabs">
          <i class="iconfont icon-close" @click="handleHide"></i>
          <el-tabs v-model="activeName" @tab-click="handleClick">
            <el-tab-pane :label="$t('common.notification.systemInformation')" name="first">
              <div class="normal-note-right-header-btn flex-x" :class="isShowNotice && 'normal-note-right-header-btn-notice'">
              
                <div
                  :class="['flex-x' ,'curs-point', 'color-666 curs-point', 'notice-info-manager']"
                  v-if="isShowNotice"
                  @click="openTabNoticeList"
                >
                  <i class="iconfont icon-caidan_xinxiguanli font-12 mar-r-5"></i>
                  {{$t('common.notification.informationAnnouncementManagement')}}
                </div>
                
                <div
                  :class="['flex-x' ,'curs-point',read_all?'color-primary curs-ban':'color-666 curs-point']"
                  @click="clear_note('all')"
                >
                  <i class="iconfont icon-quanbuyidu font-12 mar-r-5"></i>
                  {{$t('common.notification.fullBidRead')}}
                </div>
                
              </div>
              <div class="normal-note-right-list" v-if="note_arr && note_arr.length>0">
                <div
                  v-for="(item,index) in note_arr"
                  :class="['flex-x','normal-note-right-item',note_index === index?'normal-note-right-item-chosed':'']"
                  :key="index"
                  @click.stop="showItem(index)"
                >
                  <div class="normal-note-right-item-img">
                    <img :src="getImg(item.source)" alt />
                  </div>
                  <div class="flex-1">
                    <div class="flex-x">
                      <div
                        class="normal-note-right-item-title flex-1 overHideCon-1"
                      >{{getTitle(item)}}</div>
                      <div class="normal-note-right-item-time">{{item.createTime | noteTime}}</div>
                    </div>
                    <div class="flex-x">
                      <div class="normal-note-right-item-con flex-1 overHideCon-1">{{item.description}}</div>
                      <div
                        class="normal-note-right-item-number"
                        v-if="item.unReadNum>0"
                      >{{item.unReadNum > 99? 99 :item.unReadNum}}</div>
                    </div>
                  </div>
                </div>
              </div>
              <no-data-view-new v-else-if="note_arr.length == 0 && !loading" :notice-msg="$t('common.notification.noMessageNotification')"></no-data-view-new>
            </el-tab-pane>
            <el-tab-pane :label="$t('common.notification.insideInformation')" name="second" v-if="showIm">
              <InsideIM
                :list="chatList"
                :isactive="isactive"
                @clickCustomer="clickCustomer(arguments)" 
                @change="showPop()" 
                @search="searchChat($event)" 
              />
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>
      <div :class="['normal-note-left-box width500',chat_index > -1?'normal-note-left-box-show500':'']">
        <ICChat />
      </div>
      <div :class="['normal-note-left-box',note_index > -1?'normal-note-left-box-show':'']">
        <!-- normal-note-left-filter start -->
        <div class="normal-note-left-filter">
          <div class="flex-x mar-b-12">
            <div class="normal-note-left-filter-title flex-1">{{$t('system.notificationCenter.text1')}}：</div>
            <div
              :class="['flex-x','mar-r-12',readNoteAll?'color-primary curs-ban':'color-666 curs-point']"
              @click="clear_note('now_all')"
            >
              <i class="iconfont icon-quanbuyidu font-12 mar-r-5"></i>
              {{$t('common.notification.fullBidRead')}}
            </div>
          </div>
          <div class="flex-x normal-note-left-filter-list mar-b-30">
            <div
              v-for="(item, index) in date_arr"
              :key="index"
              :class="['normal-note-left-filter-item',searchModel.date_index===index?'normal-note-left-filter-item-chosed':'']"
              @click="change_filter_item('date_index',index)"
            >{{item.name}}</div>
          </div>

          <div class="normal-note-left-filter-title mar-b-12">{{$t('system.notificationCenter.text2')}}：</div>

          <div class="flex-x normal-note-left-filter-list">
            <div
              v-for="(item, index) in state_arr"
              :key="index"
              :class="['normal-note-left-filter-item',searchModel.state_index===index?'normal-note-left-filter-item-chosed':'']"
              @click="change_filter_item('state_index',index)"
            >{{item.name}}</div>
            
          </div>
        </div>
        <!-- normal-note-left-filter end -->
        <!-- normal-note-left-data start -->
        <div class="normal-note-left-data">
          <keep-alive>
            <component
              :is="'new-note-center'"
              ref="newNoteCenter"
              @clearNum="clearNum"
              @getNum="getNum"
            ></component>
          </keep-alive>
        </div>
        <!-- normal-note-left-data end -->
      </div>
    </div>
  </base-panel>
</template>

<script>
import http from '@src/util/http';
import newNoteCenter from './notificationCenter/newNoteCenter';
import { formatDate, nearDateBy, dayTimeEnd, isString, isNumber } from 'pub-bbx-utils';
import * as NotificationApi from '@src/api/NotificationApi';
import * as UserCardApi from '@src/api/UserCard'
import NoDataViewNew from '@src/component/common/NoDataViewNew';

import { openTabNoticeList } from '@src/util/business/openTab'
import { t } from '@src/locales'
import { getOssUrl, getLocalesCommonOssUrl } from '@src/util/assets'
// 引入图片
const note_img_1 = getOssUrl('/noteCenter/task.png');
const note_img_2 = getOssUrl('/noteCenter/workBench.png');
const note_img_3 = getOssUrl('/noteCenter/part.png');
const note_img_4 = getOssUrl('/noteCenter/approve.png');
const note_img_5 = getOssUrl('/noteCenter/daily.png');
const note_img_6 = getOssUrl('/noteCenter/value.png');
const note_img_7 = getOssUrl('/noteCenter/inTime.png');
const note_img_8 = getOssUrl('/noteCenter/permissions.png');
const note_img_9 = getOssUrl('/noteCenter/info.png');
const note_img_10 = getOssUrl('/noteCenter/wiki.png');
const note_img_11 = getOssUrl('/noteCenter/system.png');
const note_img_12 = getOssUrl('/noteCenter/attention.png');
// 日历
const calendar = getOssUrl('/noteCenter/calendar.png');
const Conversation_img = getOssUrl('/noteCenter/Conversation.png');
// to do 
const note_img_13 = getOssUrl('/noteCenter/shopOrder.png');
const note_img_14 = getOssUrl('/noteCenter/callcenter.png');
const note_img_15 = getOssUrl('/noteCenter/returnCenter.jpg');
const note_img_16 = getOssUrl('/noteCenter/yuncang.png');
const note_img_17 = getOssUrl('/noteCenter/sendRepair.jpg');
const note_img_18 = getOssUrl('/noteCenter/paas.png');
const note_img_19 = getOssUrl('/noteCenter/customer_experience.png');
const note_img_20 = getOssUrl('/noteCenter/projectManage.png');
const note_img_21 = getOssUrl('/noteCenter/trainManage.png');
const note_img_25 = getOssUrl('/noteCenter/invoice.png');
const note_img_26 = getLocalesCommonOssUrl('/note/qualificationManagement.png');
const note_img_27 = getLocalesCommonOssUrl('/note/taskReminder.png');
const trigger = getOssUrl('/noteCenter/trigger.png');
const smartPlan = getOssUrl('/noteCenter/smartPlan.png');
const note_img_30 = getLocalesCommonOssUrl('/note/login.png');

import _ from 'lodash'
import * as IMApi from '@src/api/ImApi.js';

import InsideIM from './InternalCoordination/insideIM/index';
import ICChat from '@src/modules/system/frame/component/InternalCoordination/chat/index.vue' 
import { openAccurateTab } from '@src/util/platform'
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'

import { BaseSelectUserModeEnum } from '@src/component/common/BaseSelectUser'
import { getRootWindow } from '@src/util/dom';

export default {
  name: 'notification-center',
  components: {
    [newNoteCenter.name]: newNoteCenter,
    [NoDataViewNew.name]: NoDataViewNew,
    InsideIM,
    ICChat
  },
  props: {
    info: Object,
    allCount: {
      type: Number,
      default: 0
    },
    isShowNotice: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      Conversation_img,
      ConversationInfo:{},
      component: 'job-notification',
      show: false,
      loading: true,
      note_obj: {
        trigger: {
          img: trigger,
          title: t('common.notification.module.label22')
        },
        SMART_PLAN_TASK_CREATE_ERROR: {
          img: smartPlan,
          title: t('smartPlan.title')
        },
        task: {
          img: note_img_1,
          title: t('common.base.task')
        },
        event: {
          img: note_img_2,
          title: t('common.notification.module.label1')
        },
        spare: {
          img: note_img_3,
          title: t('common.base.sparePart')
        },
        approve: {
          img: note_img_4,
          title: t('common.notification.module.label2')
        },
        daily: {
          img: note_img_5,
          title: t('common.notification.module.label3')
        },
        performance: {
          img: note_img_6,
          title: t('common.notification.module.label4')
        },
        timing: {
          img: note_img_7,
          title: t('common.notification.module.label5')
        },
        authority: {
          img: note_img_8,
          title: t('common.notification.module.label6')
        },
        notice: {
          img: note_img_9,
          title: t('common.notification.module.label8')
        },
        wiki: {
          img: note_img_10,
          title: t('common.notification.module.label7')
        },
        system: {
          img: note_img_11,
          title: t('common.notification.systemInformation')
        },
        attention: {
          img: note_img_12,
          title: t('common.notification.module.label16')
        },
        // to do 
        shopOrder: {
          img: note_img_13,
          title: t('common.notification.module.label17')
        },
        call: {
          img: note_img_14,
          title: t('common.notification.module.label15')
        },
        exchange: {
          img: note_img_15,
          title: t('common.notification.module.label11')
        },
        CloudWareHouse: {
          img: note_img_16,
          title: t('common.notification.module.label20')
        },
        sendRepair: {
          img: note_img_17,
          title: t('common.notification.module.label21')
        },
        paas_approve: {
          img: note_img_18,
          title: t('common.notification.module.label9')
        },
        workMessage: {
          img: note_img_18,
          title: t('common.notification.module.label13')
        },
        satisfaction: {
          img: note_img_19,
          title: t('common.notification.module.label14')
        },
        project:{
          img: note_img_20,
          title: t('common.notification.module.label23')
        },
        course:{
          img: note_img_21,
          title: t('common.notification.module.label24')
        },
        invoice: {
          img: note_img_25,
          title: t('common.notification.module.label25')
        },
        qualificationManagement:{
          img: note_img_26,
          title: t('common.notification.module.label26')
        },
        taskReminder:{
          img: note_img_27,
          title: t('common.notification.module.label28')
        },
        login:{
          img: note_img_30,
          title: t('common.notification.module.label30')
        }
      },
      note_arr: [],
      note_index: -1,
      now_note: -1,
      chat_index: -1,
      date_arr: [
        { name: t('common.base.all'), value: 'all' },
        { name: t('task.components.taskAllotModal.today'), value: 0 },
        { name: t('task.components.taskAllotModal.yesterday'), value: 1 },
        { name: t('system.notificationCenter.text3'), value: 6 },
        { name: t('system.notificationCenter.test7'), value: 29 }
      ],
      state_arr: [
        { name: t('common.base.all'), value: '' },
        { name: t('common.base.notRead'), value: '' },
        { name: t('common.base.haveRead'), value: '' }
      ],
      searchModel: {
        date_index: 0,
        state_index: 0
      },
      readedParams: {
        0: '',
        1: '0',
        2: '1'
      },
      nowInfo: {},
      windowInnerHeight: 0,
      activeName: 'first',
      chatList: [],
      isactive: '',
      chatInfo:{},
      showIm: false,
      openCallBack: null,
    };
  },
  filters: {
    noteTime(value) {
      if(!value) return ''
      let time_source = formatDate(value, 'YYYY-MM-DD');
      let time_now = formatDate(new Date(), 'YYYY-MM-DD');
      let res;
      if (time_now === time_source) {
        res = formatDate(value, 'HH:mm');
      } else {
        res = formatDate(value, 'YYYY-MM-DD');
      }
      return res;
    }
  },
  methods: {
    // pass通知的图片默认note_img_18
    getImg(source) {
      return this.note_obj?.[source]?.img ?? note_img_18
    },
    // pass通知的title取templateName
    getTitle(obj) {
      return this.note_obj?.[obj.source]?.title ?? obj?.templateName ?? ''
    },
    handleClick(tab, event) {
      this.note_index = -1
      this.now_note = -1
      this.chat_index = -1
      this.isactive = ''
      tab.name === 'second' && this.$track.clickStat(this.$track.formatParams('INTERNAL_NOTIFICATION_TAB'));
    },
    async clear_note(type) {
      if (type == 'all' && this.allCount <= 0) {
        return;
      }
      if (type == 'now_all') {
        if (this.note_arr[this.note_index].unReadNum <= 0) {
          return;
        }
        // let haveNotRead = this.$refs.newNoteCenter.haveNotRead();
        // if (!haveNotRead) return;
      }
      let confirm_con = {
        all: this.$t('system.notificationCenter.text4'),
        now_all: this.$t('system.notificationCenter.text5')
      };
      let confirm_res = await this.$platform.confirm(confirm_con[type]);
      if (!confirm_res) {
        return;
      }
      if (type == 'all') {
        NotificationApi.newGetMessageMark().then(result => {
          if (result.status == 0) {
            this.$refs.newNoteCenter.clearAllRead();
            if (this.note_arr && this.note_arr.length > 0) {
              this.note_arr.forEach(item => {
                item.unReadNum = 0;
              });
            }
            this.$emit('clearNum', { count: '-1' });
          }
        });
      } else {
        let { startTime, endTime } = this.choseTime;
        let source = this.note_arr[this.note_index].source;
        let count = this.note_arr[this.note_index].unReadNum * 1;

        NotificationApi.newGetMessageMark({
          source,
          startTime,
          endTime
        }).then(result => {
          if (result.status == 0) {
            this.$emit('clearNum', {
              count: count || 0
            });
            this.note_arr[this.note_index].unReadNum = 0;
            this.$refs.newNoteCenter.clearAllRead();
          }
        });
      }
    },
    showComponent() {
      this.show = true;
    },
    handleHide(){
      this.show = false
    },
    clearNum(e) {
      let source = this.note_arr[this.note_index].source;
      let { id } = e;
      if (e.readed == 1) {
        if (e.needHide) {
          this.hideItem();
        }
        return;
      }
      NotificationApi.newGetMessageMark({
        source,
        id
      }).then(result => {
        if (result.status == 0) {
          this.note_arr[this.note_index].unReadNum -= e.count || 0;
          this.$emit('clearNum', e);

          if (e.needHide) {
            this.hideItem();
          }
        }
      });
    },
    getNum(count) {
      if (this.allCount != count) {
        this.$emit('getNum');
      }
    },
    // new 通知中心
    async showItem(index) {
      if (this.now_note !== index) {
        this.$set(this.searchModel, 'state_index', 0);
        this.$set(this.searchModel, 'date_index', 0);
        this.now_note = index;
        this.$refs.newNoteCenter.changeParams({
          source: this.note_arr[index].source,
          readed: this.readedParams[this.searchModel.state_index],
          ...this.choseTime
        });
      }
      this.note_index = this.note_index == index ? -1 : index;
    },
    //  外部掉用打开通知中心
    outShowItem(source) {
      this.show = true;
      if (source == 'notice') {
        // 打开信息公告
        this.openCallBack = function () {
          const index = this.note_arr.findIndex(v => v.source === source);
          if (index < 0) return;
          this.showItem(index);
        }
      }
    },
    OnlineService(){
      openAccurateTab({
        type: PageRoutesTypeEnum.PageImImchat
      })
    },
    hideItem() {
      this.note_index = -1;
    },
    change_filter_item(key, val) {
      if (this.searchModel[key] == val) return;
      this.searchModel[key] = val;
      this.$refs.newNoteCenter.changeParams({
        source: this.note_arr[this.note_index].source,
        readed: this.readedParams[this.searchModel.state_index],
        ...this.choseTime
      });
    },
    loadData() {
      this.loading = true;
      NotificationApi.newGetMessageGroup().then(result => {
        if (result.status == 0) {
          let num = 0;
          if (result.data && result.data.length > 0) {
            // 过滤掉不属于规定source的异常数据（新需求：pass流程通知按照模版，动态的）
            for (let index = result.data.length - 1; index >= 0; index--) {
              const currentSource = result.data?.[index]?.source ?? ''
              if (!this.note_obj.hasOwnProperty(currentSource) && currentSource.indexOf('paas_template_') < 0) {
                result.data.splice(index, 1);
              } else {
                num += result.data[index].unReadNum * 1;
              }
            }
            this.getNum(num);
          }

          this.note_arr = result.data || [];
          this.loading = false;
          this.openCallBack?.();
        }
      }).finally(()=>{
        this.openCallBack = null
      })
    },
    async checkCalendar(){
      // 获取是否开通日历
      try {
        const { data } = await http.get('/calendar/check');
        if(data) {
          this.note_obj = Object.assign(this.note_obj, {calendar:{img: calendar, title: this.$t('common.schedule.title')}});
        }
      } catch (error) {
        console.error('error', error);
      }
      this.loadData();
    },
    GetConversation(){
      IMApi.getTotalUnreadCount()
        .then(res=>{
          if(res.code === 0){
            this.ConversationInfo = res.data
            this.$emit('ConversationSum', res.data.unreadCount)
          }
        })
    },
    openTabNoticeList() {
      openTabNoticeList()
      this.handleHide()
    },
    async getChatList(keywords = '') {
      let param = {
        keywords
      }
      let res = await IMApi.queryPersonalChatList(param)
      if (res.success) {
        this.chatList = res.data || []
        // 如果是从点击卡片消息过来的 跳转到指定的会话
        let ImCardChatUuid = sessionStorage.getItem('ImCardChatUuid') || ''
        if(ImCardChatUuid){
          this.chatList.map((item, index) => {
            if (item.chatUuid === ImCardChatUuid) {
              this.chat_index = index
              this.isactive = item.chatUuid
              this.clickCustomer([item, index])
            }
          })
          sessionStorage.removeItem('ImCardChatUuid')
        }
      }
    },
    searchChat(keywords) {
      this.getChatList(keywords)
    },
    // 读取消息
    async chatMessageRead(obj){
      try{
        const params = {
          chatUuid: obj.chatUuid,
          chatType: obj.chatType,
          chatUnreadMessageIdList: obj.chatUnreadMessageIdList,
        }
        const {code} = await IMApi.chatMessageRead(params)
        if(code == 0){
          const idx = this.chatList.findIndex(v=>v.chatUuid === obj.chatUuid)
          this.chatList[idx].chatUnreadCount = 0
        }
      }catch(err){
        return Promise.reject(this.$t('common.notification.ChatMessageReadCallFailed'))
      }

    },
    // 内部消息列表选择出现聊天
    clickCustomer(param) {
      let chat = param[0]
      this.$emit('clearNum', {
        count: chat?.chatUnreadCount || 0
      });
      if (chat.chatType === 2 && chat.errorChat) {
        return this.$confirm(this.$t('common.notification.groupChatDeleted'), this.$t('common.base.toast'), {
          confirmButtonText: this.$t('common.base.iKnow'),
          // cancelButtonText: '取消',
          showCancelButton: false,
          type: 'warning'
        }).then(async () => {
          IMApi.chatDisplay({
            chatType: chat.chatType,
            chatUuid: chat.chatUuid,
          }).then(res => {
            if (res.code === 0) {
              this.$eventBus.$emit('getChatList');
              if(this.chatItemInfo.chatUuid == chat.chatUuid){
                this.$eventBus.$emit('closeChat')
              }
            }
          });
        }).catch(() => {});
      }
      // if(chat.errorChat){
      //   return this.$message.error('该用户不存在')
      // }
      this.chat_index = param[1];
      this.isactive = param[0].chatUuid
      this.chatInfo = chat
      this.$eventBus.$emit('initPage_insideIM', chat)
      this.$eventBus.$emit('clear_chat_msg')
      sessionStorage.setItem('chatParams', JSON.stringify(chat))
      if (chat.chatUnreadCount > 0) {
        this.chatMessageRead(chat)
      }
    },
    // 点击➕选人聊天
    showPop() {
      // 打开选人弹窗
      let options = {
        title: this.$t('system.notificationCenter.text6'),
        seeAllOrg: true,
        min: 1,
        max: 9,
        mode: BaseSelectUserModeEnum.Filter
      };
      
      /** 
       * FIXME: 选人组件
      */
      this.$fast.select.multi.departmentAndUser(options).then((result = {}) => {
        if(result.status == 0){
          let data = result.data || {};
          let users = data.users || [];
          let depts = data.depts || [];
          // this.activeUser = users[0]
          // this.singleChat(users[0].userId)
          const ids = users.map(v => v.userId)
          const tagIdList = depts.map(v => v.id)
          this.startChat({ memberUserIdList:ids, tagIdList })
        }
      })
        .catch(err => console.error(err))
    },
    // 内部消息卡片点击回调
    async insideImCardCb(chatUuid) {
      this.$nextTick(()=>{
        this.show = true
        this.activeName = 'second'
      })
      if(this.chatList?.length == 0) return
      this.chatList.map((item, index) => {
        if (item.chatUuid === chatUuid) {
          this.chat_index = index
          this.isactive = item.chatUuid
          this.clickCustomer([item, index])
        }
      })
      sessionStorage.removeItem('ImCardChatUuid')
    },
    startChat(params) {
      this.$nextTick(()=>{
        this.show = true
        this.activeName = 'second'
      })
      let that = this
      IMApi.startChat(params).then(res => {
        if (res.success) {
          IMApi.queryPersonalChatList().then(result => {
            if (result.success) {
              that.chatList = result.data || []
              that.chatList.map((item, index) => {
                if (item.chatUuid === res.data.chatUuid) {
                  that.chat_index = index
                  that.isactive = item.chatUuid
                  // that.$eventBus.$emit('initPage_insideIM', item)
                  that.clickCustomer([item, index])
                  sessionStorage.setItem('chatParams', JSON.stringify(item))
                }
              })
            }
          })
        }else{
          this.$message.error(res.message)
          sessionStorage.setItem('chatError', true);
        }
      })
    },
    // websocket通知 chatNewMessageCb 
    chatNewMessageCb(data){
      if(this.chatInfo.chatUuid == data.content.chatUuid && this.chat_index != -1 && data.content?.messageLevel !== 2){
        // 处于当前聊天且打开了聊天窗口把消息读取
        this.chatMessageRead({
          chatUuid:data.content.chatUuid,
          chatType:data.content.chatType,
          chatUnreadMessageIdList:[ data.content.id ],
        }).then(res=>{
          const idx = this.chatList.findIndex(v=>v.chatUuid === data.content.chatUuid)
          this.chatList[idx].chatUnreadCount = 0
        })
      }else{
        // 不处于当前聊天刷新列表
        this.getChatList()
      }
    },
    closeChat(){
      this.chat_index = -1
    },
    // 获取内部协同IM是否开启
    getUserCardConfig(){
      let that = this
      UserCardApi.getUserCardConfig().then(res=>{
        if(res.status == 0){
          this.showIm = res.data.showIm
          if (res.data.showIm) {
            that.getChatList()
          }
        }else{
          this.$platform.toast(res.message, 'error')
        }
      })
    },
    // 更新当前列表聊天信息
    updateCurrentChat(msg) {
      const index = this.chatList.findIndex(v => v.chatUuid === msg.chatUuid)
      if (index > -1) this.chatList[index].recentMessage = msg?.recentMessage;
    }
  },
  computed: {
    choseTime() {
      let value = this.date_arr[this.searchModel.date_index].value;
      if(isNumber(value)) {
        return { 
          startTime: value < 30 ? +nearDateBy(value) : null,
          endTime: +dayTimeEnd(nearDateBy(value === 1 ? 1 : 0)),
        };
      }

      return {
        startTime: null,
        endTime: null,
      }
    },
    read_all() {
      return this.allCount <= 0;
    },
    readNoteAll() {
      return !(
        this.note_arr[this.now_note]
        && this.note_arr[this.now_note].unReadNum > 0
      );
    },
  },
  created(){
    window.onbeforeunload = function(){
      // 刷新页面清除chatParams,inside_cardInfo,chatShow
      sessionStorage.removeItem('chatParams')
      sessionStorage.removeItem('inside_cardInfo')
      sessionStorage.removeItem('chatShow')
      sessionStorage.removeItem('chatError')
    }
    this.$eventBus.$on('websocket_insideIm', (data)=>{
      let notifyType = data.notifyType
      if (
        [
          'chatNewMessage',
          'chatGroupNewMessage',
          'chatNewGroup',
          'groupDynamic',
        ].includes(notifyType)
      ) {
        this.chatNewMessageCb(data);
      }
    })
    this.$eventBus.$on('closeChat', this.closeChat)
    this.$eventBus.$on('getChatList', this.getChatList)
    this.$eventBus.$on('updateCurrentChat', this.updateCurrentChat)
    window.insideImCardCb = this.insideImCardCb
    window.startChat = this.startChat
  },
  mounted() {
    this.$eventBus.$on('hideNotificationPanel', this.handleHide)
    // 有竞态问题，直接请求不从localStorage中获取

    this.getUserCardConfig()
  },
  destroyed(){
    this.$eventBus.$off('websocket_insideIm')
    this.$eventBus.$off('closeChat')
    this.$eventBus.$off('getChatList')
    this.$eventBus.$off('updateCurrentChat')
  },
  watch: {
    show: {
      handler(newValue) {
        if (newValue == false) {
          this.note_index = -1;
          this.now_note = -1;
          this.chat_index = -1;
          this.isactive = '';
          // this.activeName = 'first';
          sessionStorage.removeItem('chatParams')
          sessionStorage.removeItem('chatShow')
          sessionStorage.removeItem('chatError')
        } else {
          this.checkCalendar();
          if(this.activeName == 'second'){
            this.getChatList()
            sessionStorage.setItem('chatShow', 1)
          }
        }
      }
    },
    activeName(newValue){
      if(newValue == 'second'){
        this.getChatList()
        sessionStorage.setItem('chatShow', 1)
      }else{
        sessionStorage.removeItem('chatShow')
      }
    }
  }
};
</script>

<style lang="scss">
.notification-center {
  top: 50px;
  display: flex;
  flex-flow: column;
  background: #eee;
  overflow: none;
  box-shadow: -3px 0px 5px #ccc;
  ::-webkit-scrollbar {
    display: none;
  }
}
.notification-center-header {
  height: 50px;
  line-height: 50px;
  background: #55b7b4;
  text-align: center;
  font-size: 18px;
  padding: 0 2px;
}
.notification-center-btn {
  float: left;
  height: 50px;
}
.notification-center-title {
  display: inline-block;
  margin: 0;
  color: #fff;
}
.notification-center-type {
  display: flex;
  text-align: center;
  list-style: none;
  height: 65px;
  padding: 0 13px;
  font-size: 16px;
  background: #fff;
  z-index: 100;
  span {
    color: #474747;
    opacity: 0.64;
  }
}
.notification-center-tab {
  display: none;
  &:checked + label {
    span {
      color: #474747;
      opacity: 1;
    }
    div:nth-child(2) {
      min-width: 18px;
      height: 18px;
      position: absolute;
      top: 20px;
      left: 145px;
      font-size: 13px;
      padding: 0 5px;
      color: #fff;
      background: #cb0c0c;
      border-radius: 12px;
      opacity: 1;
    }
  }
}
.notification-center-tab-left {
  &:checked + label {
    div:nth-child(3) {
      position: absolute;
      top: 62px;
      left: 330px;
      height: 5px;
      width: 28px;
      z-index: 99;
      border-radius: 5px;
      background: #55b7b4;
      transition: all 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);
      transform: translateX(-233px);
    }
  }
}
.notification-center-tab-right {
  &:checked + label {
    div:nth-child(3) {
      position: absolute;
      top: 62px;
      left: -137px;
      height: 5px;
      width: 28px;
      z-index: 99;
      border-radius: 5px;
      background: #55b7b4;
      transition: all 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);
      transform: translateX(233px);
    }
  }
}
.notification-center-tab-text {
  position: relative;
  padding-top: 30px;
  margin: 0;
  flex: 1;
  background: #fff;
  border-bottom: 1px solid #cbcbcb;
  user-select: none;
  &:hover {
    cursor: pointer;
  }
}
.notification-center-tab-new {
  min-width: 18px;
  height: 18px;
  position: absolute;
  top: 20px;
  left: 145px;
  font-size: 13px;
  padding: 0 5px;
  color: #fff;
  background: #cb0c0c;
  border-radius: 12px;
  opacity: 0.64;
}
.notification-center-tab-number {
  position: relative;
  top: -5px;
  font-size: 8px;
  color: #fff;
}
.notification-close {
  color: #fff;
  font-size: 18px;
}
.icon-notification {
  margin-right: 5px;
  font-size: 18px;
}
.icon-fenzu {
  color: #fff;
  font-size: 18px;
}
.notification-center-close {
  float: right;
  height: 50px;
}

// new 通知中心
.flex-x {
  display: flex;
  align-items: center;
}
.flex-1 {
  flex: 1;
}
.color-666 {
  color: #666;
  .iconfont {
    color: #999;
  }
}
.font-12 {
  font-size: 12px;
}
.mar-r-5 {
  margin-right: 5px;
}
.mar-r-12 {
  margin-right: 12px;
}
.mar-b-12 {
  margin-bottom: 12px;
}
.mar-b-30 {
  margin-bottom: 30px;
}
.overHideCon-1 {
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 1;
  overflow: hidden;
  white-space: normal;
  word-wrap: break-word;
  word-break: break-all;
}
.normal-note-box {
  width: 400px;
  position: absolute;
  min-height: 300px;
  max-height: 100%;
  height:calc(100% - 50px) !important;
  right: 0;
  z-index: 99;
  box-shadow: none !important;
}
//  normal-note-right-box  start
.normal-note-right-box {
  width: 400px;
  height: 100%;
  overflow-y: scroll;
  right: 0;
  z-index: 99;
  background: rgba(245, 250, 250, 1);
  box-shadow: -6px 0px 16px 0px rgba(0, 0, 0, 0.1);
  .normal-note-right-header {
    position: sticky;
    position: -webkit-sticky;
    top: 0;
    z-index: 98;
    width: 100%;

    .normal-note-right-header-title {
      background: $color-primary;
      color: #fff;
      width: 100%;
      text-align: center;
      height: 48px;
      font-size: 18px;
      line-height: 48px;
      font-weight: 500;
    }
  }
  .normal-note-right-header-btn {
    width: 100%;
    height: 48px;
    padding: 0 16px;
    justify-content: flex-end;
    background: rgba(245, 250, 250, 1);
  }

  .normal-note-right-list {
    padding: 0 16px;
    // height: 100%;
    box-sizing: border-box;
    height: calc(100% - 48px);
    overflow-y: auto;
    & .normal-note-right-item {
      margin-bottom: 12px;
    }
    & .normal-note-right-item-chosed {
      box-shadow: 0px 3px 6px 0px rgba(0, 0, 0, 0.12);
    }
    .normal-note-right-item {
      cursor: pointer;
      padding: 14px 12px;
      background: #fff;
      border-radius: 4px;
      min-height: 68px;
      .normal-note-right-item-img {
        width: 40px;
        height: 40px;
        border-radius: 50%;
        // background: #ff0000;
        margin-right: 11px;
        img {
          width: 100%;
          height: 100%;
        }
      }
      .normal-note-right-item-title {
        font-size: 16px;
        font-weight: 500;
      }
      .normal-note-right-item-con {
        color: $text-color-secondary;
        font-size: 12px;
      }
      .normal-note-right-item-time {
        color: $text-color-secondary;
        font-size: 12px;
      }
      .normal-note-right-item-number {
        width: 18px;
        height: 18px;
        border-radius: 50%;
        background: #f56c6c;
        text-align: center;
        font-size: 12px;
        line-height: 18px;
        color: #fff;
      }
    }
  }
}
//  normal-note-right-box  end
//  normal-note-left-box  start
.normal-note-left-box {
  width: 400px;
  background: rgba(245, 250, 250, 1);
  position: absolute;
  height: 100%;
  overflow-y: scroll;
  transform: translateX(0);
  transition: all 0.3s;
  scrollbar-width: none; /* Firefox */
  -ms-overflow-style: none; /* IE 10+ */
  z-index: 97;
  .normal-note-left-filter {
    background: #fff;
    padding: 16px 4px 20px 16px;
    position: sticky;
    position: -webkit-sticky;
    top: 0;
    box-shadow: 0px 6px 16px 0px rgba(0, 0, 0, 0.1);
    z-index: 98;
    .normal-note-left-filter-title {
      font-size: 16px;
      font-weight: 500;
    }
    .normal-note-left-filter-list {
      flex-wrap: wrap;
      & .normal-note-left-filter-item {
        margin-right: 12px;
      }
      .normal-note-left-filter-item {
        cursor: pointer;
        width: 170px;
        height: 28px;
        line-height: 28px;
        text-align: center;
        border-radius: 4px;
        border: 1px solid rgba(220, 230, 230, 1);
        box-sizing: border-box;
        margin-bottom:5px;
      }
      .normal-note-left-filter-item-chosed {
        background: $color-primary;
        border: none;
        color: #fff;
      }
    }
  }
  .normal-note-left-data {
    height: 100%;
  }
}
//  normal-note-left-box  end
.normal-note-left-box-show {
  transform: translateX(-400px);

  box-shadow: -6px 0px 16px 0px rgba(0, 0, 0, 0.1);
}
.curs-point {
  cursor: pointer;
}
.curs-ban {
  cursor: not-allowed;
}
.color-primary {
  @include fontColor();
}

.normal-note-right-header-btn-notice {
  justify-content: space-between !important;
}

.normal-tabs{
  position: relative;
  height: 100%;
  i.icon-close{
    position: absolute;
    right: 20px;
    top: 10px;
    font-size: 14px;
    z-index: 99;
    cursor: pointer;
  }
  .el-tabs__header{
    margin-bottom: 0;
  }
  .el-tabs__nav{
    margin-left: 32px;
    .el-tabs__item{
      text-align: center;
    }
  }
  .el-tabs{
    height: 100%;
    display: flex;
    flex-direction: column;
  }
  .el-tabs__content{
    flex: 1;
    .el-tab-pane{
      height: 100%;
    }
  }
}
.width500{
  width: 400px;
}
.normal-note-left-box-show500{
  transform: translateX(-400px);
  box-shadow: -6px 0px 16px 0px rgba(0, 0, 0, 0.1);
}
</style>
